<template>
  <div class="form-page">
    <Card :bordered="false" :dis-hover="true">
      <p slot="title" style="color: #666;">
        <span
          class="iconfont icon-changyongtubiao-xianxingdaochu-zhuanqu-"
          style="font-size: 20px;"
        ></span> 新增活动
      </p>
      <p slot="extra" style="color: #999;font-size: 12px;">
        <label style="color: #FF3B30;">*</label> 为必填
      </p>
      <div class="company-box">
        <div>
          <Row type="flex" justify="start" align="middle">
            <div class="divider-short"></div>
            1号抽奖池(有限池)
          </Row>

          <Form ref="formModel" :rules="ruleValidate1" :model="bloc.form.activity1" :label-width="150"
                label-position="right">
            <FormItem label="活动名称:" prop="ActivityName" required>
              <Input v-model="bloc.form.activity1.ActivityName" placeholder="最多15个字" :maxlength="15" class="wid"/>
            </FormItem>
            <FormItem label="抽奖所需积分:" prop="PointsNeed" required>
              <Input v-model="bloc.form.activity1.PointsNeed" prop="pointsNeed" placeholder="抽奖所需积分" class="wid"/>
            </FormItem>
            <FormItem label="用户默认抽奖次数:" prop="InvovleTimes" required>
              <Input v-model="bloc.form.activity1.InvovleTimes" prop="invovleTimes" placeholder="用户默认抽奖次数" class="wid"/>
            </FormItem>
            <FormItem label="持续时间:" required>
              <Row>
                <Col span="11">
                  <FormItem prop="StartTime">
                    <DatePicker style="width: 100%;" type="datetime" format="yyyy-MM-dd HH:mm" placeholder="开始时间" v-model="bloc.form.activity1.StartTime"></DatePicker>
                  </FormItem>
                </Col>
                <Col span="2" style="text-align: center">-</Col>
                <Col span="11">
                  <FormItem prop="EndTime">
                    <DatePicker style="width: 100%;" type="datetime" format="yyyy-MM-dd HH:mm" placeholder="结束时间" v-model="bloc.form.activity1.EndTime"></DatePicker>
                  </FormItem>
                </Col>
              </Row>
            </FormItem>
            <Card v-for="(award, index) in bloc.awards" :key="index" class="award-item">
              <FormItem label="奖品名称:" required>
                <input v-model="award.name" placeholder="奖品名字" class="ivu-input"/>
              </FormItem>
              <FormItem label="奖品数量:" required>
                <input type="number" v-model="award.quantity" placeholder="奖品数量" class="ivu-input" />
              </FormItem>
              <FormItem label="奖品概率(%):" required>
                <input type="number" v-model="award.probability" :max="100" :min="0" placeholder="奖品概率(%)" class="ivu-input"/>
              </FormItem>
              <FormItem label="是否为高价值奖品:">
                <i-switch v-model="award.isValue"></i-switch>
              </FormItem>
              <FormItem label="奖品图片:" required>
                <div class="video">
                  <div class="demo-upload-list" v-for="(item, index) in fileList" :key="index">
                    <template v-if="item.status1 === 'finished'">
                      <img :src="item.imageurl">
                      <div class="demo-upload-list-cover">
                        <Icon type="ios-eye-outline" @click.native="handleView(item.imageurl)"></Icon>
                        <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                      </div>
                    </template>
                    <template v-else>
                      <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                    </template>
                  </div>
                  <Upload
                    ref="upload"
                    :show-upload-list="false"
                    :action="imageAndVideoPath"
                    :max-size="maxSize"
                    :format="['jpg','png']"
                    :headers="uploadHeaders"
                    :on-format-error="handleFormatError1"
                    :on-exceeded-size="handleMaxSize1"
                    :on-success="handleSuccess(index)"
                    :before-upload="beforeupload"
                    style="display: inline-block;width:58px;margin-left:15px"
                  >
                    <div style="width: 58px;height:58px;line-height: 58px;">
                      <Icon type="ios-camera" size="20"></Icon>
                    </div>
                    <Modal title="View Image" v-model="visible">
                      <img :src="imgUrl" v-if="visible" style="width: 100%">
                    </Modal>
                  </Upload>
                </div>
                <div style="margin-top: 10px"><p>支持 JPG、PNG格式，图片小于2M</p></div>
              </FormItem>
            </Card>
            <Button type="primary" style="width: 100px;height: 20px;" :loading="bloc.loading"
                    @click="addAward(1)"> 添加奖品
            </Button>
          </Form>


        </div>

        <div>
          <Row type="flex" justify="start" align="middle">
            <div class="divider-short"></div>
            2号抽奖池(无限池)
          </Row>
          <Form ref="formOtherModel" :rules="ruleValidate2" :model="bloc.form.activity2" :label-width="150"
                label-position="right">
            <FormItem label="活动名称:" prop="activityName2" required>
              <Input v-model="bloc.form.activity2.ActivityName" placeholder="最多15个字" :maxlength="15" class="wid"/>
            </FormItem>
            <FormItem label="抽奖所需积分:" prop="pointsNeed2" required>
              <Input v-model="bloc.form.activity2.PointsNeed" prop="pointsNeed" placeholder="抽奖所需积分" class="wid"/>
            </FormItem>
            <FormItem label="用户默认抽奖次数:" prop="invovleTimes2" required>
              <Input v-model="bloc.form.activity2.InvovleTimes" prop="invovleTimes" placeholder="用户默认抽奖次数" class="wid"/>
            </FormItem>

            <FormItem label="持续时间:" required>
              <Row>
                <Col span="11">
                  <FormItem prop="StartTime">
                    <DatePicker style="width: 100%;" type="datetime" format="yyyy-MM-dd HH:mm" placeholder="开始时间" v-model="bloc.form.activity2.StartTime"></DatePicker>
                  </FormItem>
                </Col>
                <Col span="2" style="text-align: center">-</Col>
                <Col span="11">
                  <FormItem prop="EndTime">
                    <DatePicker style="width: 100%;" type="datetime" format="yyyy-MM-dd HH:mm" placeholder="结束时间" v-model="bloc.form.activity2.EndTime"></DatePicker>
                  </FormItem>
                </Col>
              </Row>
            </FormItem>

            <Card v-for="(award, index) in bloc.awards2" :key="index" class="award-item">
              <FormItem label="奖品名称:" required>
                <input v-model="award.name" placeholder="奖品名字" class="ivu-input"/>
              </FormItem>
              <FormItem label="奖品数量:">
                <input type="number" v-model="award.quantity" placeholder="奖品数量" class="ivu-input" />
              </FormItem>
              <FormItem label="奖品概率(%):" required>
                <input type="number" v-model="award.probability" :max="100" :min="0" placeholder="奖品概率(%)" class="ivu-input"/>
              </FormItem>
              <FormItem label="是否为高价值奖品:">
                <i-switch v-model="award.isValue" disabled></i-switch>
              </FormItem>
              <FormItem label="奖品图片:" required>
                <div class="video">
                  <div class="demo-upload-list" v-for="(item, index) in fileList2" :key="index">
                    <template v-if="item.status1 === 'finished'">
                      <img :src="item.imageurl">
                      <div class="demo-upload-list-cover">
                        <Icon type="ios-eye-outline" @click.native="handleView(item.imageurl)"></Icon>
                        <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                      </div>
                    </template>
                    <template v-else>
                      <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                    </template>
                  </div>
                  <Upload
                    ref="upload"
                    :show-upload-list="false"
                    :action="imageAndVideoPath"
                    :max-size="maxSize"
                    :format="['jpg','png']"
                    :headers="uploadHeaders"
                    :on-format-error="handleFormatError1"
                    :on-exceeded-size="handleMaxSize1"
                    :on-success="handleSuccess2(index)"
                    :before-upload="beforeupload"
                    style="display: inline-block;width:58px;margin-left:15px"
                  >
                    <div style="width: 58px;height:58px;line-height: 58px;">
                      <Icon type="ios-camera" size="20"></Icon>
                    </div>
                    <Modal title="View Image" v-model="visible">
                      <img :src="imgUrl" v-if="visible" style="width: 100%">
                    </Modal>
                  </Upload>
                </div>
                <div style="margin-top: 10px"><p>支持 JPG、PNG格式，图片小于2M</p></div>
              </FormItem>
            </Card>
            <Button style="width: 100px;height: 20px;" :loading="bloc.loading"
                    @click="addAward(2)"> 添加奖品
            </Button>
          </Form>
        </div>
      </div>
      <div style="margin: 20px 0px 35px 25px;">
        <Button style="width: 100px;height: 40px;" @click="handleCancel()">返回</Button>
        <Button type="primary" style="margin-left: 30px;width: 100px;height: 40px;" :loading="bloc.loading"
                @click="handleOk()">保存
        </Button>
      </div>
    </Card>
  </div>
</template>

<script lang="ts">
    import {Component, Vue} from 'vue-property-decorator';
    import {store} from '@/store/Store';
    import {baseUrl} from '@/base/Request';
    import {Route} from 'vue-router';
    import {FormBloc} from './ActivityAddBloc';
    import {isEmpty} from '@/base/util/Strings';
    import {AppButton} from '@/type/AppButton';
    import { FormItem } from 'view-design';

    @Component({
    })

    export default class extends Vue {
        disabled: boolean = true;
        beforeRouteEnter(to: Route, from: Route, next: (vm: any) => void) {
            next(vm => {
                vm.bloc.type = vm.tepee;
                vm.bloc.form.activity1.Isfinite = 1;
                // if (vm.isHasMemberInfo) {
                //     vm.bloc.getCompanyList(vm.bloc.company.pageIndex, vm.bloc.company.pageSize, 'ASC');
                // } else {
                //     this.$Message.error('加载失败');
                // }
            });
        }
        bloc = new FormBloc();
        get tepee() {
            return store.state.user.tepee
        }
        get uploadHeaders() {
            return {
                'Authorization': 'Bearer ' + store.state.auth.accessToken
            }
        };
        imgUrl = '';
        visible = false;

        get fileList() {
            return this.bloc.fileList.map(x => {
                return {'name': 'name', 'imageurl': x, 'status1': 'finished'};
            });
        }
        get fileList2() {
            return this.bloc.fileList2.map(x => {
                return {'name': 'name', 'imageurl': x, 'status1': 'finished'};
            });
        }
        // get isHasMemberInfo() {
        //     const sessinStr = sessionStorage.getItem('MEMBER_INFO');
        //     const info = sessinStr ? JSON.parse(sessinStr) : undefined;
        //     if (info) {
        //         this.bloc.model.companyId = info[0].companyId;
        //         this.bloc.getAllSort(1, 100, 'ASC');
        //         this.bloc.model.agentId = info[0].agentId;
        //         this.bloc.model.targetAccounts = info.map((x) => x.id);
        //         this.bloc.model.targetGroup = 'PART_MEMBER';
        //         this.bloc.isinfo = true;
        //     }
        //     return !isEmpty(info);
        // }
        handleView(url) {
            this.imgUrl = url;
            this.visible = true;
        }
        handleRemove(file) {
            this.bloc.fileList.splice(this.bloc.fileList.indexOf(file), 1);
        }

        ruleValidate1: any = {
            ActivityName: [{required: true, message: '名称不能为空', trigger: 'blur'}],
            pointsNeed: [{required: true, message: '抽奖所需积分不能为空', trigger: 'blur'}],
            invovleTimes: [{required: true, message: '用户默认抽奖次数不能为空', trigger: 'blur'}],
            startTime: [{required: true, type: 'date', message: '请选择开始时间', trigger: 'change'}],
            endTime: [{required: true, type: 'date', message: '请选择结束时间', trigger: 'change'}]
        };
        ruleValidate2: any = {
            activityName2: [{required: true, message: '名称不能为空', trigger: 'blur'}],
            pointsNeed2: [{required: true, message: '抽奖所需积分不能为空', trigger: 'blur'}],
            invovleTimes2: [{required: true, message: '用户默认抽奖次数不能为空', trigger: 'blur'}],
            startTime2: [{required: true, type: 'date', message: '请选择开始时间', trigger: 'change'}],
            endTime2: [{required: true, type: 'date', message: '请选择结束时间', trigger: 'change'}]
        };

        enable = false;
        length1 = 0;
        length2 = 0;

        addAward(num) {
            if (num === 1) {
                this.bloc.awards.push({ name: '', quantity: 1, probability: 0, imgUrl: '', isValue: 0 });
                this.length1 = this.bloc.awards.length - 1;
            } else {
                this.bloc.awards2.push({ name: '', quantity: 1, probability: 0, imgUrl: '', isValue: 0 });
                this.length2 = this.bloc.awards2.length - 1;
            }
        }

        // 添加
        // addModel(name) {
        //     this.$refs[name].validate(valid => {
        //         if (valid) {
        //             this.$refs.save.bloc.loading = true;
        //             if (isNaN(this.bloc.model.agentId)) {
        //                 this.bloc.model.agentId = 1;
        //             }
        //             if (this.tepee !== '1') {
        //                 this.bloc.model.agentId = store.state.user.agent.id;
        //                 this.bloc.model.companyId = store.state.user.agent.companyId;
        //             }
        //
        //             if (this.bloc.model.startTime) {
        //                 this.bloc.model.startTime = this.bloc.model.startTime.getTime()
        //             }
        //             if (this.bloc.model.endTime) {
        //                 this.bloc.model.endTime = this.bloc.model.endTime.getTime()
        //             }
        //             this.bloc.addModel(this.bloc.model).then(res => {
        //                 this.$Message.success('确认成功');
        //                 this.$refs.save.bloc.loading = false;
        //                 this.handleOK();
        //             }).catch(err => {
        //                 // this.$Message.error('保存失败');
        //                 this.$Message.error(err.message);
        //                 this.$refs.save.bloc.loading = false;
        //             });
        //         }
        //     });
        // }
        imageAndVideoPath = '';
        maxSize = 2048;
        elProgress=false;
        isimage : boolean | undefined;
        handleProgress() {
            this.elProgress = true;
        }
        handleError() {
            this.elProgress = false;
            this.$Message.error('上传失败');
        }
        beforeupload(file) {
            // this.isvideo = file.type === 'video/mp4';
            this.isimage = new RegExp('^image').test(file.type);
            if (this.isimage) {
                // this.bloc.model.type = 'IMAGE';
                return new Promise<void>((resolve) => {
                    this.$nextTick(() => {
                        this.imageAndVideoPath = `${baseUrl}/api/upload/image`;
                        this.maxSize = 2048;
                        resolve();
                    })
                })
            } else { // 如果上传文件不满足规定格式，则返回 false ，并提示，终止上传，不用配置上传路径。
                this.$Message.error('请选择格式为JPG、PNG格式的文件');
                return false;
            }
        }
        handleFormatError1(file) {
            this.$Message.error('请选择格式为JPG、PNG格式的文件')
        }
        handleMaxSize1(file) {
            this.$Message.error('图片大小不能超过2M');
        }
        handleSuccess(index) {
            const that = this;
            return function (res, file) {
                that.elProgress = false;
                if (that.isimage) {
                    that.bloc.awards[index].imgUrl = res.data[0];
                }
                if (that.bloc.fileList.length > 0) {
                    that.bloc.fileList = []
                }
                that.bloc.fileList.push(that.bloc.awards[index].imgUrl)
            };
        }
        handleSuccess2(index) {
            const that = this;
            return function (res, file) {
                that.elProgress = false;
                if (that.isimage) {
                    that.bloc.awards2[index].imgUrl = res.data[0];
                }
                if (that.bloc.fileList2.length > 0) {
                    that.bloc.fileList2 = []
                }
                that.bloc.fileList2.push(that.bloc.awards2[index].imgUrl)
            };
        }
        handleCancel() {
            this.$router.push({path: `/activity`});
        }
        handleOk() {
            let probabilityCount1: number = 0;
            let probabilityCount2: number = 0;
            const formRef: any = this.$refs['formModel'];
            const formOtherRef: any = this.$refs['formOtherModel'];

            formRef.validate((valid) => {
                if (valid) {
                    const validPrize = this.bloc.awards.every(award => {
                       probabilityCount1 = probabilityCount1 + award.probability;
                       return award.name.trim() !== '' && award.probability !== 0 && award.quantity !== 0 && award.imgUrl !== ''
                    });
                    if (!validPrize) {
                        this.$message.error('请检查1号奖池的奖品信息，确保每个奖品的名称和图片都不为空，数量和概率不等于0');
                        return;
                    }
                    if (probabilityCount1 !== 100) {
                        this.$message.error('请检查1号奖池的奖品概率，其概率总和应为100%');
                        return;
                    }

                    formOtherRef.validate((otherValid) => {
                        if (otherValid) {
                            const validPrize2 = this.bloc.awards2.every(award2 => {
                                probabilityCount2 = probabilityCount2 + award2.probability;
                                return award2.name.trim() !== '' && award2.probability !== 0 && award2.quantity !== 0 && award2.imgUrl !== ''
                            });
                            if (!validPrize2) {
                                this.$message.error('请检查2号奖池的奖品信息，确保每个奖品的名称和图片都不为空，数量和概率不等于0');
                                return;
                            }
                            if (probabilityCount2 !== 100) {
                                this.$message.error('请检查2号奖池的奖品概率，其概率总和应为100%');
                                return;
                            }
                            this.saveFn();
                        }
                    });
                }
            });
        }
        saveFn() {
            // if (this.getValidate()) return;
            this.bloc.loading = true;
            console.log(this.bloc.form.activity1, this.bloc.form.activity2);
            console.log(this.bloc.awards, this.bloc.awards2)
            // const parmas = this.isAdd ? '' : this.idx;
            this.bloc.addActivity().then(res => {
                this.$Message.success('保存成功');
                this.bloc.loading = false;
                this.handleCancel();
            }).catch(err => {
                this.bloc.loading = false;
                this.$Message.error('保存失败');
                console.log('出错啦::::', err);
            });
        }
    }
</script>

<style lang="less" scoped>
  /deep/ .ivu-form-item-content {
    justify-content: start !important;
    align-items: center !important;
  }
  /deep/ .ivu-form-item-label {
    padding-top: 0;
  }
  .company-box {
    display: flex;
    justify-content: space-around;
  }
  .divider-short {
    width: 4px;
    height: 24px;
    background: #0079FE;
    margin-right: 10px;
  }
  .ivu-row-flex-middle {
    font-weight: bolder;
    font-size: 16px;
    margin-bottom: 28px;
  }
  .wid {
    width: 400px;
  }
  .award-item {
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08);
    margin-bottom: 20px;
  }
</style>
